const CFG = require('./config');
const rCache = require('./model/redis_cache');
const EC = require('./comm/err-code');
const helper = require('./comm/api-helper');
const mqttConn = require('./utils/mqttConn');
const FUN = require('./comm/func');
const express = require('express');
const cors = require('cors');
const https = require('https');
const http = require('http');
const fs = require('fs');

// 检测是不是本地运行
if (FUN.isLocal()) {
  console.log("\n\nIs Local Host:", require("os").hostname());
} else {
  console.log("\n\nIs Remote Srv:", require("os").hostname());
}

// 清除token
// rCache.delNode(rCache.N_UserAuth);

FUN.SleepMs(2000); // 延时两秒等mqtt服务器启动完成

// 启动mqtt单一连接
mqttConn.singleClient('admin.8'+FUN.rand(12345678,99999999));

// 解析policy数据
helper.PolicyJsonToCache();

// 创建主应用
let options = { // ssl配置
  key:fs.readFileSync(CFG.QlinkApi.ssl_key),
  cert:fs.readFileSync(CFG.QlinkApi.ssl_crt)
}
const app = express();
var httpsServer = https.createServer(options, app);
var httpServer = http.createServer(app);

app.use(cors()); // 跨站处理
app.use(express.urlencoded({extended:true})); // 传参编码处理
app.use(express.json()); // 传参编码处理

// 调试打印
app.use((req, resp, next) => {
  console.log('[REQ] %s %s %s [%s]', req.ip, req.method, req.url, req.body.token);
  next();
})

//路由定义
app.use('/policy-data', require('./api/policy-data'));
app.use('/policy-type', require('./api/policy-type'));
app.use('/policy', require('./api/policy-item'));
app.use('/user-auth', require('./api/user-auth'));
app.use('/device', require('./api/device'));
app.all('/*',(req,resp)=>{resp.json({code:EC.NOT_FOUNT,data:[]})});

// 监听服务器
httpServer.listen(CFG.QlinkApi.port);
httpsServer.listen(CFG.QlinkApi.ssl_port);
console.log('Start listen web port', CFG.QlinkApi.port, CFG.QlinkApi.ssl_port);
